const IndexUtils = require('./index')
const config = require('../../static/config')
const {formatUrl, getTaskId} = require('./utils')
const reg = require('./req')
const request = reg.getInstance()

export function makeRequest(method, options, onSuccess, onError) {
  let op = Object.assign({
    maxRetry: 2,
    maxRetryMessage: '超过重试次数',
  }, options)
  let r = {}
  r.context = {}
  r.baseUrl = config.request.base + options.action
  r.url = ''
  r.id = ''
  r.retry = -1
  r.lastSendArgs = []
  r.makeUrl = function(args, h) {
    r.retry = 0
    r.url = formatUrl(r.baseUrl, args, h)
    r.id = getTaskId(r.url)
    return r
  }
  r.requestObj = reg.makeRequest({
    onSecond(request) {
      r.retry = r.retry + 1
      if (r.retry < op.maxRetry) {
        r.send.apply(r, r.lastSendArgs)
      } else {
        console.log(op.maxRetryMessage)
      }
    }
  })
  r.send = (params = {}, next = function(){}) => {
    r.lastSendArgs = [
      params, next
    ]
    r.requestObj[method](
      r.url,
      params
    ).then((res) => {
      onSuccess && onSuccess(res, r.context, next)
    }).catch(e => {
      onError && onError(e, r.context)
    })
  }
  r.bind = function (context) {
    r.context = context
  }
  return r
}

export function makeGetRequest(options = {}, onSuccess, onError) {
  return makeRequest('get', options, onSuccess, onError)
}

export function makePostRequest(options = {}, onSuccess, onError) {
  return makeRequest('post', options, onSuccess, onError)
}

export function makePutRequest(options = {}, onSuccess, onError) {
  return makeRequest('put', options, onSuccess, onError)
}

const Auth = require('./auth')

/**
 * 获取学员登录token
 *
 * @param code
 * @param extraData
 *
 {
	"uid": "636363",
	"provider": "weixin",
	"extra_data": "{}"
 }
 * @param appendData
 * @param query
 * @returns {*}
 */
export function commonTokenCreate(code, extraData = {}, appendData = {}, query = '') {
  // let request = IndexUtils.initRequest()
  // request.needHandleErr = false
  // return request.post(
  //   formatUrl(config.request.base + '/common/token/create'),
  //   {
  //     uid,
  //     "provider": "weixin",
  //     extra_data: JSON.stringify(extraData)
  //   }
  // )
  let _url = formatUrl(config.request.base + '/token/create/')
  return new Promise((resolve, reject) => {
    wx.request({
      method: 'POST',
      url: _url + (query ? `?${query}` : ''),
      header: {
        ['auth-sys']: 'agent',
        ['appVersion']: config.appVersion
      },
      data: {
        uid: code,
        'provider': 'weixin',
        extra_data: JSON.stringify(extraData),
        ...appendData,
      },
      success(e) {
        if (!e.data) {
          reject(new Error('oh'))
        }
        console.log('e.data', e, e.data)
        if (e.statusCode !== 200) {
          wx.showToast({
            title: `网络错误 ${e.statusCode}`,
            icon: 'none'
          })
        }

        if (e.data.code === 61001) {
          reject(new Error('61001 error'))
        }

        if (e.data.data) {
          Auth.setToken(e.data.data.token)
        }

        resolve(e.data)
      },
      fail(e) {
        console.error('native error', e)
        wx.showToast({
          title: `网络错误`,
          icon: 'none'
        })
        // reject(e)
      },
    })
  })
}

/**
 * 学员注册
 *
 * @param data
 * @param query
 * @returns {*}
 */
export function registerStudent(data = {}, query = '') {
  return request.post(
    formatUrl(config.request.base + `/user/create/`) + (query ? `?${query}` : ''),
    {
      provider: 'weixin',
      ...data,
      'extra_data': '{}',
    },
  )
}

/**
 * 获取注册状态
 *
 * @param params
 * @returns {*}
 */
export function getRegisterStatus(params) {
  let searchOpt = {}
  return request.get(
    formatUrl(config.request.base + '/register/status'),
    {
      ...searchOpt,
      ...params,
    },
  )
}


